package vn.com.baseapplication.activity;

import java.util.Arrays;
import java.util.List;

import vn.com.baseapplication.BaseActivity;
import vn.com.baseapplication.R;
import vn.com.baseapplication.util.FBUtils;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.facebook.Request;
import com.facebook.Request.GraphUserCallback;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.FacebookDialog;

public abstract class FBBaseLoginActivity extends BaseActivity {

	protected Session fbSession = null;
	protected SessionState fbSsState = SessionState.CLOSED;
	protected GraphUser user;
	private UiLifecycleHelper uiHelper;
	protected StatusCallback fbSsCallback = new Session.StatusCallback() {

		// callback when session changes state
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			fbSession = session;
			fbSsState = state;

			if (exception != null) {
				Log.e("FbError", exception.getMessage().toString(),
						exception.fillInStackTrace());
				FBBaseLoginActivity.this.onFailed(session, state, exception);
			}
			if (session.isOpened()) {
				// make request to the /me API
				Request.newMeRequest(session, new GraphUserCallback() {

					@Override
					public void onCompleted(final GraphUser user,
							final Response response) {
						FBBaseLoginActivity.this.user = user;
						FBBaseLoginActivity.this.runOnUiThread(new Runnable() {

							@Override
							public void run() {
								FBBaseLoginActivity.this.onCompleted(user,
										response);
							}
						});
					}
				}).executeAsync();
			}
		}
	};

	public void onCompleted(GraphUser user, Response response) {
		
	}

	public void onFailed(Session session, SessionState state,
			Exception exception) {
		FBUtils.getHashKeySentToFB(getApplicationContext(), "");
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		uiHelper = new UiLifecycleHelper(this, fbSsCallback);
		uiHelper.onCreate(savedInstanceState);
	}

	@Override
	protected void onResume() {
		super.onResume();
		uiHelper.onResume();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode,
				resultCode, data);

		uiHelper.onActivityResult(requestCode, resultCode, data,
				new FacebookDialog.Callback() {
					@Override
					public void onError(FacebookDialog.PendingCall pendingCall,
							Exception error, Bundle data) {
						Log.e("Activity",
								String.format("Error: %s", error.toString()));
						onShareFbComplete(pendingCall, error, data);
					}

					@Override
					public void onComplete(
							FacebookDialog.PendingCall pendingCall, Bundle data) {
						Log.i("Activity", "Success!");
						onShareFbComplete(pendingCall, null, data);
					}
				});
	}

	public void shareFb(String name, String caption, String link,
			String picture, String description, List<String> friends) {
		FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(this)
				.setLink(link).setCaption(caption).setPicture(picture)
				.setDescription(description).setFriends(friends).setName(name)
				.build();
		uiHelper.trackPendingDialogCall(shareDialog.present());
	}
	
	public void onShareFbComplete(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data){
		
	}

	public void connectFacebookAccount() {
		Session session = Session.getActiveSession();
	    if (!session.isOpened() && !session.isClosed()) {
	        session.openForRead(new Session.OpenRequest(this)
	            .setPermissions(Arrays.asList("basic_info","email","user_birthday"))
	            .setCallback(fbSsCallback));
	    } else {
	        Session.openActiveSession(this, true, fbSsCallback);
	    }
//		Session.openActiveSession(this, true, fbSsCallback);
	}

	public void disconnectFacebookAccount() {
		showProgressDialog("Disconnecting Facebook account...");

		new AsyncTask<Void, Void, Boolean>() {
			@Override
			protected Boolean doInBackground(Void... params) {
				if (Session.getActiveSession() != null)
					Session.getActiveSession().closeAndClearTokenInformation();

				clearFacebookInfoFromSharedPreferences();

				// perform any other operations you need to do perform here
				// such as clearing local database tables and so forth

				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				showProgressDialog(null);
				// safety check
				if (isFinishing())
					return;

				if (result == null || result == false)
					onFailedFacebookDisconnect();
				else
					onSucceededFacebookDisconnect();
			}
		}.execute();
	}

	protected void onSucceededFacebookDisconnect() {
		onCompleted(null, null);
	}

	protected void onFailedFacebookDisconnect() {

	}

	protected void clearFacebookInfoFromSharedPreferences() {

	}

	AlertDialog dialogFb;

	private void showProgressDialog(String message) {
		if (message == null) {
			dialogFb.dismiss();
			return;
		}
		String logout = getResources().getString(
				R.string.com_facebook_loginview_log_out_action);
		// String cancel =
		// getResources().getString(R.string.com_facebook_loginview_cancel_action);
		if (user != null && user.getName() != null) {
			message = String.format(
					getResources().getString(
							R.string.com_facebook_loginview_logged_in_as),
					user.getName());
		} else {
			message = getResources().getString(
					R.string.com_facebook_loginview_logged_in_using_facebook);
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(message).setPositiveButton(logout,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						fbSession.closeAndClearTokenInformation();
					}
				});
		dialogFb = builder.create();
		dialogFb.show();
	}
}
